package com.apartment.own.service.impl;

import java.util.*;

import com.apartment.common.exception.CustomException;
import com.apartment.common.utils.DateUtils;
import com.apartment.common.utils.SecurityUtils;
import com.apartment.common.utils.StringUtils;
import com.apartment.own.domain.OwnResArticleInventory;
import com.apartment.own.domain.constant.ClassNameConstants;
import com.apartment.own.mapper.OwnResArticleInventoryMapper;
import com.apartment.own.request.res.ResArticleTemplateDTO;
import com.apartment.own.service.IOwnResArticleInventoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.apartment.own.mapper.OwnResArticleTemplateMapper;
import com.apartment.own.domain.OwnResArticleTemplate;
import com.apartment.own.service.IOwnResArticleTemplateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 物品模板Service业务层处理
 *
 * @author @Dog_E
 * @date 2020-08-28
 */
@Service
public class OwnResArticleTemplateServiceImpl extends ServiceImpl<OwnResArticleTemplateMapper, OwnResArticleTemplate> implements IOwnResArticleTemplateService {
    @Autowired
    private OwnResArticleTemplateMapper ownResArticleTemplateMapper;
    @Autowired
    private IOwnResArticleInventoryService resArticleInventoryService;
    @Autowired
    private OwnResArticleInventoryMapper ownResArticleInventoryMapper;

    /**
     * 查询物品模板
     *
     * @param id 物品模板ID
     * @return 物品模板
     */
    @Override
    public OwnResArticleTemplate selectOwnResArticleTemplateById(Long id) {
        return ownResArticleTemplateMapper.selectOwnResArticleTemplateById(id);
    }

    /**
     * 查询物品模板列表
     *
     * @param ownResArticleTemplate 物品模板
     * @return 物品模板
     */
    @Override
    public List<OwnResArticleTemplate> selectOwnResArticleTemplateList(OwnResArticleTemplate ownResArticleTemplate) {
        return ownResArticleTemplateMapper.selectOwnResArticleTemplateList(ownResArticleTemplate);
    }

    /**
     * 新增物品模板
     *
     * @param ownResArticleTemplate 物品模板
     * @return 结果
     */
    @Override
    public int insertOwnResArticleTemplate(OwnResArticleTemplate ownResArticleTemplate) {
        ownResArticleTemplate.setCreateTime(DateUtils.getNowDate());
        return ownResArticleTemplateMapper.insertOwnResArticleTemplate(ownResArticleTemplate);
    }

    /**
     * 修改物品模板
     *
     * @param ownResArticleTemplate 物品模板
     * @return 结果
     */
    @Override
    public int updateOwnResArticleTemplate(OwnResArticleTemplate ownResArticleTemplate) {
        ownResArticleTemplate.setUpdateTime(DateUtils.getNowDate());
        return ownResArticleTemplateMapper.updateOwnResArticleTemplate(ownResArticleTemplate);
    }

    /**
     * 批量删除物品模板
     *
     * @param ids 需要删除的物品模板ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteOwnResArticleTemplateByIds(Long[] ids) {
        //1.先删除模板下的物品
        ArrayList<Long> longs = new ArrayList<>(Arrays.asList(ids));
        //2.删除该模板下的所有物品
        ownResArticleInventoryMapper.delete(
                Wrappers.<OwnResArticleInventory>lambdaQuery()
                        //根据模板id 和 表关系 删除
                        .in(OwnResArticleInventory::getForeignId, longs)
                        .eq(OwnResArticleInventory::getSurfaceName, ClassNameConstants.OWN_RES_ARTICLE_TEMPLATE_FK_OWN_RES_ARTICLE_INVENTORY)
        );
        //2.删除模板
        return ownResArticleTemplateMapper.deleteOwnResArticleTemplateByIds(ids);
    }

    /**
     * 删除物品模板信息
     *
     * @param id 物品模板ID
     * @return 结果
     */
    @Override
    public int deleteOwnResArticleTemplateById(Long id) {
        return ownResArticleTemplateMapper.deleteOwnResArticleTemplateById(id);
    }

    /**
     * @param templateDTO: 物品模板DTO
     * @Description: 添加模板与详情
     * @return: int
     * @Author: @Dog_E
     * @Date: 2020/9/8 0008 13:54
     **/
    @Override
    @Transactional
    public int addTemplateAndArticle(ResArticleTemplateDTO templateDTO) {
        //创建一个新的ArrayList 用于接收前端(难以实现的功能)呵呵!
        List<OwnResArticleInventory> articles = new ArrayList<>();
        if (Objects.nonNull(templateDTO.getPublicGoods())) articles.addAll(templateDTO.getPublicGoods());
        if (Objects.nonNull(templateDTO.getRoomItems())) articles.addAll(templateDTO.getRoomItems());

        if (Objects.isNull(articles)) {
            throw new CustomException("物品不能为空");
        }
        OwnResArticleTemplate ownResArticleTemplate = new OwnResArticleTemplate();
        //1.添加模板
        BeanUtils.copyProperties(templateDTO, ownResArticleTemplate);
        //添加模板创建人 id
        ownResArticleTemplate.setCreateBy(SecurityUtils.getUser().getUserId().toString());
        //添加模板时间
        ownResArticleTemplate.setCreateTime(new Date());
        //查询重复的模板名称 区别合租整租
        List<OwnResArticleTemplate> list = list(
                new QueryWrapper<OwnResArticleTemplate>().lambda()
                        .eq(OwnResArticleTemplate::getTemplateType, ownResArticleTemplate.getTemplateType()));

        if (StringUtils.isEmpty(ownResArticleTemplate.getTemplateName())) {
                throw new CustomException("模板名称不能为空");
        }
        for (OwnResArticleTemplate DBTemplate : list) {
            //名字相同抛出异常
            if (ownResArticleTemplate.getTemplateName().equals(DBTemplate.getTemplateName())) {
                throw new CustomException("模板名称已存在");
            }
        }
        save(ownResArticleTemplate);
        //2.物品添加
        articles.forEach(article -> {
            //添加创建人 id
            article.setCreateBy(SecurityUtils.getUser().getUserId().toString());
            //添加时间
            article.setCreateTime(new Date());
            //物品详细添加外检id
            article.setForeignId(ownResArticleTemplate.getId());
            //物品详细添加关系
            article.setSurfaceName(ClassNameConstants.OWN_RES_ARTICLE_TEMPLATE_FK_OWN_RES_ARTICLE_INVENTORY);
        });
        //添加物品
        return resArticleInventoryService.saveBatch(articles) ? 1 : 0;
    }

    /**
     * @param id: 模板id
     * @Description: 查询物品模板对应的物品
     * @return: java.util.List<com.apartment.own.domain.OwnResArticleInventory> 物品清单
     * @Author: @Dog_E
     * @Date: 2020/9/8 0008 15:42
     **/
    @Override
    public List<OwnResArticleInventory> articleList(String id) {
        if (StringUtils.isNull(id)) {
            throw new CustomException("物品模板id不能为空");
        }
        //根据模板ID 和 表关系进行查询
        List<OwnResArticleInventory> list = ownResArticleInventoryMapper.selectList(
                new QueryWrapper<OwnResArticleInventory>().lambda()
                        .eq(OwnResArticleInventory::getForeignId, id)
                        .eq(OwnResArticleInventory::getSurfaceName, ClassNameConstants.OWN_RES_ARTICLE_TEMPLATE_FK_OWN_RES_ARTICLE_INVENTORY)
        );
        return list;
    }

    /**
     * @param templateDTO: 物品模板与物品 类
     * @Description: 修改物品模板与物品
     * @return: com.apartment.common.core.domain.AjaxResult
     * @Author: @Dog_E
     * @Date: 2020/9/8 0008 18:26
     **/
    @Override
    @Transactional
    public int updateTemplateAndArticle(ResArticleTemplateDTO templateDTO) {

        //创建一个新的ArrayList 用于接收前端(难以实现的功能)呵呵!
        List<OwnResArticleInventory> articles = new ArrayList<>();
        if (Objects.nonNull(templateDTO.getPublicGoods())) articles.addAll(templateDTO.getPublicGoods());
        if (Objects.nonNull(templateDTO.getRoomItems())) articles.addAll(templateDTO.getRoomItems());


        OwnResArticleTemplate ownResArticleTemplate = new OwnResArticleTemplate();
        BeanUtils.copyProperties(templateDTO, ownResArticleTemplate);
        //1.修改模板name
        //1.1查询重复的模板名称 区别合租整租
        List<OwnResArticleTemplate> list = list(
                new QueryWrapper<OwnResArticleTemplate>().lambda()
                        .eq(OwnResArticleTemplate::getTemplateType, ownResArticleTemplate.getTemplateType()));
        if (StringUtils.isEmpty(ownResArticleTemplate.getTemplateName())) {
            throw new CustomException("模板名称不能为空");
        }
        for (OwnResArticleTemplate DBTemplate : list) {
            //名字相同抛出异常
            if (!DBTemplate.getId().equals(templateDTO.getId()) && DBTemplate.getTemplateName().equals(ownResArticleTemplate.getTemplateName())) {
                throw new CustomException("模板名称已存在");
            }
        }

        //更改模板名称
        update(ownResArticleTemplate, new UpdateWrapper<OwnResArticleTemplate>()
                .lambda()
                .eq(OwnResArticleTemplate::getId, ownResArticleTemplate.getId()));

        //2.删除该模板下的所有物品
        ownResArticleInventoryMapper.delete(
                Wrappers.<OwnResArticleInventory>lambdaQuery()
                        //根据模板id 和 表关系 删除
                        .eq(OwnResArticleInventory::getForeignId, ownResArticleTemplate.getId())
                        .eq(OwnResArticleInventory::getSurfaceName, ClassNameConstants.OWN_RES_ARTICLE_TEMPLATE_FK_OWN_RES_ARTICLE_INVENTORY)
        );

        //3.重新添加物品
        articles.forEach(article -> {
            //添加创建人 id
            article.setCreateBy(SecurityUtils.getUser().getUserId().toString());
            //添加时间
            article.setCreateTime(new Date());
            //物品详细添加外检id
            article.setForeignId(ownResArticleTemplate.getId());
            //物品详细添加关系
            article.setSurfaceName(ClassNameConstants.OWN_RES_ARTICLE_TEMPLATE_FK_OWN_RES_ARTICLE_INVENTORY);
        });
        //添加物品
        return resArticleInventoryService.saveBatch(articles) ? 1 : 0;
    }


}
